import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_vehicle.dart';
import 'package:inmotion_pro/pages/models/http_response/http_response_model.dart';
import 'package:inmotion_pro/pages/others/common_enum/tbox_status_type.dart';
import 'package:inmotion_pro/service/encryption_service.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import '../custom_exception/api_exception.dart';

extension ApiHelperTboxExtension on ApiHelper {
  // MARK: - 判断该车型是否支持云盒功能
  Future<bool> checkTboxSupport(String sn, String productModel) {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v2/tbox/model",
      HttpResponseModel.fromJson,
      queryParameters: {
        "sn": sn,
        "model": productModel,
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.originalResponse.data['data'] is bool;
    });
  }

  // MARK: - 获取云盒激活状态
  Future<bool> getTboxActivationStatus(
    String sn, {
    required String tboxUserName,
    required String tboxPassword,
    required String imei,
  }) {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v2/imei/check",
      HttpResponseModel.fromJson,
      queryParameters: {
        "sn": sn,
        "data": EncryptionService.to
            .encryptString('$tboxUserName,$tboxPassword,$imei'),
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!.tboxActivated;
    });
  }

  // MARK: - 获取云盒在线状态，实则是从授权车辆列表接口获取（条件：当前用户必须是车主）
  Future<(TBoxStatus, bool)> getTboxOnlineStatus(String sn) {
    return ApiHelper().getAuthorizedVehicleList(sn: sn).then((vehicleList) {
      return vehicleList.isEmpty
          ? (TBoxStatus.none, false)
          : (vehicleList.first.tboxStatus.value, vehicleList.first.hmicStatus);
    });
  }

  // MARK: - 车辆唤醒
  Future<bool> wakeUpVehicle(String sn) {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v2/vehicle/wake-up",
      HttpResponseModel.fromJson,
      queryParameters: {
        "sn": sn,
      },
    ).then((rsp) {
      if (!rsp.isSuccess) {
        throw ApiException(rsp.code, rsp.message);
      }
      return rsp.isSuccess;
    });
  }

  // MARK: - 消息透传
  Future<String> passThrough(String sn, String data) {
    return httpManager.request<HttpResponseModel>(
      RequestType.POST,
      "/v2/pass-through",
      HttpResponseModel.fromJson,
      data: {
        "sn": sn,
        "data": data,
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      final rsp = response.originalResponse.data['data'];
      return rsp as String;
    });
  }
}
